//
//  ConversionViewController.swift
//  WorldTroter
//
//  Created by 曹宇 on 2020/5/3.
//  Copyright © 2020 曹宇. All rights reserved.
//

import Foundation
import UIKit


class ConversionViewController: ViewController,UITextFieldDelegate{
    
    @IBOutlet var celsiusLabel: UILabel!
    
    @IBAction func fahrenHeitFieldEdtingChanged(_ textField: UITextField) {
        
//        print((textField.text!) as String)
//
//        if textField.text!.count>0{
//            celsiusLabel.text = textField.text
//        }else{
//            celsiusLabel.text = "???"
//        }
        if let text = textField.text, let value = Double(text) {
//            celsiusLabel.text = String(huaToShe(temp: value))
            celsiusLabel.text = numberFormatter.string(
                from: NSNumber(value: huaToShe(temp: value)))
        }else{
            celsiusLabel.text = nil
        }
        
    }
    
    @IBOutlet var textField:UITextField!
    
    @IBAction func dismissKeyBoard(_ sender: UITapGestureRecognizer){
        textField.resignFirstResponder()
    }
    
    func huaToShe(temp:Double)->Double {
        return (temp-32)/1.8
    }
    
    let numberFormatter: NumberFormatter = {
        let nf = NumberFormatter()
        nf.numberStyle = .decimal
        nf.minimumFractionDigits = 0
        nf.maximumFractionDigits = 1
        return nf
    }()
    
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        let existDot = textField.text?.range(of: ".")
        let replaceText = string.range(of: ".")
        
        if  (existDot != nil)&&(replaceText != nil){
            return false
        }else{
            return true
        }
        
        print("\(textField.text)")
        print("\(string)")
        return true
    }
}
